package com.yan.demo.demo3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author taoge
 * @Date 2024/8/8 14:45
 * @Description 生产者消费者模式中的桌子
 */
public class Stack {
    private Product product;
    private Boolean flag;
    Lock lock = new ReentrantLock();
   Condition creat_lock = lock.newCondition();
   Condition consum_lock = lock.newCondition();

    public Stack(Product product, Boolean flag) {
        this.product = product;
        this.flag = flag;
    }

    public  void create(String name , String color){
        lock.lock();
        try {
            while (flag){
                try {
                    creat_lock.await(); //this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            product.setName(name);
            product.setColar(color);
            System.out.println(Thread.currentThread().getName() + "生产了"  + color +"的" + name);

            flag = true;
            consum_lock.signal();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public  void consume(){
        lock.lock();
        try {
            while (!flag){
                try {
                    consum_lock.await();//this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "消费了" + product.getColar() + "的" + product.getName());
            flag = false;
            creat_lock.signal();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
